package weather.util;

import java.util.*;

/**
 * Class with utilities for processing dates.
 * @author Jerzy Mazurek WEiTI PW
 */
public class Dates
{
	public static final long DAY_LENGTH_IN_HOURS = 24;
	public static final long DAY_LENGTH_IN_MINUTES = DAY_LENGTH_IN_HOURS * 60;
	public static final long DAY_LENGTH_IN_SECONDS = DAY_LENGTH_IN_MINUTES * 60;
	public static final long DAY_LENGTH_IN_MILLISECONDS = DAY_LENGTH_IN_SECONDS * 1000;
	
	/**
	 * Returns number of days between the specified dates. Returned value is based on the
	 * difference between the specified dates in milliseconds and is positive if the "earlier"
	 * date really is earlier than the "later" date. Evaluation is performed on dates cut to days.
	 * @param earlier the earlier date
	 * @param later the later date
	 * @return positive value if the "earlier" date really is earlier than the "later" date
	 */
	public static int numberOfDaysBetween(java.util.Date earlier, java.util.Date later)
	{
		return (int)((cutDateToDays(later).getTime() - cutDateToDays(earlier).getTime()) / DAY_LENGTH_IN_MILLISECONDS);
	}
	
	/**
	 * Returns the specified date cut to days, e.g. for '14 JUL 2009 13:45'
	 * returned value is '14 JUL 2009 00:00'.
	 * @param date date to cut
	 * @return cut date
	 */
	public static java.util.Date cutDateToDays(java.util.Date date)
	{
		Calendar calendar = GregorianCalendar.getInstance();
		int[] fieldsToReset = {Calendar.HOUR_OF_DAY,
				Calendar.MINUTE,
				Calendar.SECOND,
				Calendar.MILLISECOND};
		
		calendar.setTime(date);
		
		for (int field: fieldsToReset)
			calendar.set(field, calendar.getActualMinimum(field));
		
		return calendar.getTime();
	}
}
